<template>
  <!-- 搜索框 -->
  <el-card style="height: 80px">
    <el-form :model="queryForm" :inline="true" class="form">
      <el-form-item label="用户名:">
        <el-input
            v-model="queryForm.queryName"
            placeholder="请输入用户名"
        ></el-input>
      </el-form-item>
      <el-form-item label="角色:">
        <el-select
            v-model="queryForm.role"
            placeholder="请选择角色"
            style="width: 200px"
            clearable
        >
          <el-option label="全部" :value="0"></el-option>
          <el-option label="管理员" :value="1"></el-option>
          <el-option label="用户" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="default" @click="search">
          搜索
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 添加用户和批量删除 -->
  <el-card style="margin: 10px 0">
    <el-tooltip effect="dark" content="添加" placement="top">
      <el-button type="success" size="default" icon="Plus" @click="handleAdd">
      </el-button>
    </el-tooltip>
    <!-- table展示用户信息 -->
    <el-table style="margin: 10px 0" border :data="userTableData">
      <el-table-column
          label="用户名"
          align="center"
          prop="username"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="电话"
          align="center"
          prop="phone"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="邮箱"
          align="center"
          prop="email"
          show-overflow-tooltip
      ></el-table-column>
      <el-table-column
          label="角色"
          align="center"
          prop="type"
          show-overflow-tooltip
          :formatter="(row: any) => {
        const roleMap: Record<number, string> = { 1: '管理员', 2: '用户' };
        return roleMap[row.type] || '未知角色';
      }"
      ></el-table-column>
      <el-table-column
          label="头像"
          align="center"
          prop="avatar"
      >
        <template #default="{ row }">
          <el-image
              style="width: 100px; height: 100px"
              :preview-src-list="[row.avatar]"
              :src="row.avatar"
              fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="120px" align="center">
        <template #="{ row }">
          <el-tooltip effect="dark" content="查看收货地址" placement="top">
            <el-button
                type="success"
                size="small"
                icon="Location"
                @click="handleViewAddress(row.userId)"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="编辑" placement="top">
            <el-button
                type="primary"
                size="small"
                icon="Edit"
                @click="handleEdit(row)"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="删除" placement="top">
            <el-button
                type="danger"
                size="small"
                icon="Delete"
                @click="handleDelete(row.userId)"
            >
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @current-change="findAll"
        @size-change="handler"
    />
  </el-card>

  <!-- 抽屉结构:完成添加新的用户账号|更新已有的账号信息 -->
  <el-drawer v-model="drawer" size="1000px">
    <!-- 头部标题:将来文字内容应该动态的 -->
    <template #header>
      <h4>{{ usersForm.userId ? "更新" : "添加" }}</h4>
    </template>
    <!-- 身体部分 -->
    <template #default>
      <el-form :model="usersForm" :rules="rules" ref="formRef">
        <el-form-item label="用户名" prop="username">
          <el-input
              placeholder="请您输入用户名"
              v-model="usersForm.username"
          ></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input
              placeholder="请您输电话"
              v-model="usersForm.phone"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
              placeholder="请您输入邮箱"
              v-model="usersForm.email"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="type">
          <el-select v-model="usersForm.type" placeholder="请选择角色">
            <el-option label="管理员" :value="1"></el-option>
            <el-option label="用户" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-upload
              class="upload-demo"
              :show-file-list="false"
              accept=".png,.jpg,.jpeg,.gif"
              drag
              :before-upload="handleBeforeUpload"
              :http-request="handleCustomUploadAvatar"
              multiple
          >
            <img
                style="width: 200px; height: 200px"
                v-if="usersForm.avatar"
                :src="usersForm.avatar"
                class="avatar"
                alt="图片"
            />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="drawer = false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </template>
  </el-drawer>

  <!-- 弹窗：展示收货地址 -->
  <el-dialog v-model="addressDialogVisible" title="收货地址" width="50%">
    <el-table :data="addressList" border>
      <el-table-column label="收货人" prop="username" align="center"></el-table-column>
      <el-table-column label="电话" prop="phone" align="center"></el-table-column>
      <el-table-column label="地址" prop="addressDetail" align="center" show-overflow-tooltip></el-table-column>
      <el-table-column label="默认地址" align="center">
        <template #default="{ row }">
          <el-tag v-if="row.isDefault === 1" type="success">是</el-tag>
          <el-tag v-else type="info">否</el-tag>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>
</template>

<script setup lang="ts">
import {ref, reactive, onMounted, nextTick} from "vue";
import {ElFormItem, ElMessage, ElMessageBox} from "element-plus";
import {Plus} from "@element-plus/icons-vue";
import {apiGet, apiPost} from "@/utils/api";
import { validateUtils } from "@/utils/validateUtils";
// 表单数据
let usersForm = reactive({
  userId: 0,
  username: "",
  phone: "",
  email: "",
  avatar: "",
  type: 1,
});
//搜索表单数据
let queryForm = reactive({
  queryName: "",
  role: 0,
});
//默认页码
let pageNo = ref<number>(1);
//一页展示几条数据
let pageSize = ref<number>(5);
//总个数
let total = ref<number>(0);
//存储全部用户的数组
let userTableData = ref([]);
//定义响应式数据控制抽屉的显示与隐藏 添加用户和修改用户
let drawer = ref<boolean>(false);
//获取form组件实例
let formRef = ref<any>();
// 收货地址弹窗的显示与隐藏
const addressDialogVisible = ref(false);

// 收货地址列表
const addressList = ref<Array<any>>([]);
// 查看收货地址
const handleViewAddress = async (userId: number) => {
  try {
    let {data} = await apiGet("/address/getAllByUserId", {userId});
    addressList.value = data;
    // 显示弹窗
    addressDialogVisible.value = true;
  } catch (error) {
    ElMessage.error('获取收货地址失败');
  }
};
//获取全部用户信息
let findAll = async (pager = 1) => {
  //收集当前页码
  pageNo.value = pager;
  let parameter = {
    page: pageNo.value,
    limit: pageSize.value,
    username: queryForm.queryName,
    type: queryForm.role,
  };
  //获取表单数据
  let {data} = await apiGet("/user/findAll", parameter);
  total.value = data.count;
  userTableData.value = data.data;
};

//分页器下拉菜单的自定义事件的回调
const handler = () => {
  findAll();
};

//搜索按钮的回调
const search = () => {
  findAll();
};

//添加用户按钮的回调
const handleAdd = () => {
  //抽屉显示出来
  drawer.value = true;
  //清空userParams的数据以及userParams继承User里面的所有数据
  Object.assign(usersForm, {
    userId: 0,
    username: "",
    phone: "",
    email: "",
    type: 1,
    avatar: "",
  });
  //清除上一次的错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate();
  });
};

//更新用户按钮的回调
const handleEdit = (row: any) => {
  //抽屉显示出来
  drawer.value = true;
  //将用户的信息赋值给userParams
  Object.assign(usersForm, {
    ...row,
  });
  //清除上一次的错误的提示信息
  nextTick(() => {
    formRef.value.clearValidate();
  });
};

//保存按钮的回调
const save = async () => {
  //点击保存按钮的时候,务必需要保证表单全部复合条件在去发请求
  await formRef.value.validate();
  //保存按钮:添加新的用户|更新已有的用户账号信息
  usersForm.userId
      ? await apiPost("/user/edit", {...usersForm})
      : await apiPost("/user/add", {...usersForm});
  await findAll();
  drawer.value = false;
};

//删除
const handleDelete = async (userId: number) => {
  //提示用户确认删除吗
  ElMessageBox.confirm("此操作将永久删除该用户, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
      .then(async () => {
        await apiPost("/user/delete", {userId});
        await findAll(
            userTableData.value.length > 1 ? pageNo.value : pageNo.value - 1,
        );
      })
      .catch(() => {
      });
};

//上传文件之前做的一些判断
const handleBeforeUpload = (file: any) => {
  // 检查文件类型 只能上传.png,.jpg,.jpeg,.gif
  const isExcel =
      file.type === "image/png" ||
      file.type === "image/jpg" ||
      file.type === "image/jpeg" ||
      file.type === "image/gif";
  if (!isExcel) {
    ElMessage.error("上传文件只能是.png,.jpg,.jpeg,.gif 格式!");
    return false;
  }

  //上传文件大小不能超过20M
  const isLt20M = file.size / 1024 / 1024 < 20;
  if (!isLt20M) {
    ElMessage.error("上传文件大小不能超过 20MB!");
    return false;
  }
  return isExcel && isLt20M;
};
const handleCustomUploadAvatar = async (option: any) => {
  const formData = new FormData();
  formData.append("file", option.file);
  let {msg} = await apiPost("/upload/img", formData, {
    headers: {"Content-Type": "multipart/form-data"},
  });
  usersForm.avatar = msg;
};
const validatorUserName = (rule: any, value: string, callback: any) => {
  if (value === "") {
    callback(new Error("请输入用户名"));
  } else {
    callback();
  }
};
// 手机号验证方法
const validatePhone = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error("手机号不能为空"));
  } else if (!validateUtils.validatePhone(value)) {
    callback(new Error("手机号格式不正确"));
  } else {
    callback();
  }
};
//表单校验的规则对象
const rules = {
  username: [{required: true, trigger: "blur", validator: validatorUserName}],
  phone: [{ required: true, trigger: "blur" ,validator: validatePhone}],
};

//组件挂载完毕
onMounted(() => {
  findAll();
});
</script>

<style scoped></style>
